/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package au.com.domlogic.pvc.xhtml.servlet;

import java.net.URL;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.XMLConstants;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

/**
 *
 * @author Domenic Figliomeni
 *
 *  The purpose of this servlet is to serialize the XHTML Document Object it finds
 *  on the request.
 */
public class XHTMLStrictSerializerServlet extends HttpServlet {

    private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance();
    private static final boolean VALIDATING = false;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = null;
        DOMSource source = null;
        try {
            if (request instanceof XHTMLStrictRequestWrapper) {
                response.setContentType("text/html;charset=UTF-8");
                out = response.getWriter();
                XHTMLStrictRequestWrapper rq = (XHTMLStrictRequestWrapper) request;
                Document document = rq.getDocument();
                Node root = document.getDocumentElement();
                source = new DOMSource(root);
                if (VALIDATING) {
                    URL schemaUrl = new URL("http://www.w3.org/2002/08/xhtml/xhtml1-strict.xsd");
                    SchemaFactory schemaFactory =
                            SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                    Schema schema = schemaFactory.newSchema(schemaUrl);
                    Validator validator = schema.newValidator();
                    validator.validate(source);
                }
            } else {
                throw new ServletException("The request was not a XHTMLStrictRequestWrapper.  It was a\t"
                        + request.getClass().getName());
            }
        } catch (SAXException saxe) {
            throw new ServletException(saxe);
        } finally {
            if (out != null) {
                StreamResult result = new StreamResult(out);
                if (source != null && result != null) {
                    try {
                        output(source, result);
                    } catch (Throwable t) {
                        throw new ServletException(t);
                    }
                }
                out.close();
            }
        }
    }

    private void output(DOMSource source, StreamResult result) throws TransformerConfigurationException, TransformerException {
        Transformer transformer;
        transformer = TRANSFORMER_FACTORY.newTransformer();
        transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,
                "-//W3C//DTD XHTML 1.0 Strict//EN");
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
                "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(source, result);
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
// </editor-fold>
}
